#include "main.h"

uint8_t sensor_save_cnt=0;

void eeprom_init(void)
{
	FLASH_CR1=0x00;
	FLASH_CR2=0x00;
	FLASH_NCR2=0xFF;
	FLASH_DUKR=0xae;
	FLASH_DUKR=0x56;
	while(!(FLASH_IAPSR&0x08));
}

void eeprom_write(uint8_t addr, uint8_t dat)
{
	uint8_t  *p;
	p=(uint8_t *)(0x4000+addr);
	*p=dat;
	while(!(FLASH_IAPSR&0x04));
}

uint8_t eeprom_read(uint8_t addr)
{
	uint8_t *p;
	p=(uint8_t *)(0x4000+addr); 
	return *p; 
}

void eeprom_savetime(uint16_t channel)
{
	DS1302_ReadTime(&my_time);
	eeprom_write(EE_HEAD_LENGTH+(sensor_save_cnt%150)*DATA_SIZE+0, channel);
	eeprom_write(EE_HEAD_LENGTH+(sensor_save_cnt%150)*DATA_SIZE+1, DS1302_ReadReg(DS1302_ADDR_MONTH));
	eeprom_write(EE_HEAD_LENGTH+(sensor_save_cnt%150)*DATA_SIZE+2, DS1302_ReadReg(DS1302_ADDR_DAYoM));
	eeprom_write(EE_HEAD_LENGTH+(sensor_save_cnt%150)*DATA_SIZE+3, DS1302_ReadReg(DS1302_ADDR_HOURS));
	eeprom_write(EE_HEAD_LENGTH+(sensor_save_cnt%150)*DATA_SIZE+4, DS1302_ReadReg(DS1302_ADDR_MINUTES));
	eeprom_write(EE_HEAD_LENGTH+(sensor_save_cnt%150)*DATA_SIZE+5, DS1302_ReadReg(DS1302_ADDR_SECONDS));
	// cnt++
	sensor_save_cnt++;
	// save to eeprom
	eeprom_write(EE_ADDR_CNT, sensor_save_cnt);
}

void eeprom_readtime(uint16_t cnt)
{
	my_time.century    = 20;
	my_time.year       = eeprom_read(EE_ADDR_YEAR);
	my_time.channel    = eeprom_read(EE_HEAD_LENGTH + (cnt%150-1)*DATA_SIZE + 0);
	my_time.month      = eeprom_read(EE_HEAD_LENGTH + (cnt%150-1)*DATA_SIZE + 1);
	my_time.dayofmonth = eeprom_read(EE_HEAD_LENGTH + (cnt%150-1)*DATA_SIZE + 2);
	my_time.hours      = eeprom_read(EE_HEAD_LENGTH + (cnt%150-1)*DATA_SIZE + 3);
	my_time.minutes    = eeprom_read(EE_HEAD_LENGTH + (cnt%150-1)*DATA_SIZE + 4);
	my_time.seconds    = eeprom_read(EE_HEAD_LENGTH + (cnt%150-1)*DATA_SIZE + 5);
}

void eeprom_clear_data(void)
{
	// No need to clear the flash, just reset the counter.
	sensor_save_cnt = 0;
	eeprom_write(EE_ADDR_CNT, sensor_save_cnt);
}